<?php

namespace App\Logic\Product;

use App\Core\BaseCore;
use App\Core\BaseModel;
use App\Core\Exception\DefaultException;
use App\Core\Output;
use App\Logic\Product\Form\ProductListForm;
use App\Logic\Product\Form\SubmitProductForm;
use App\Model\Product\ProductModel;
use EasySwoole\Component\Singleton;
use EasySwoole\Http\Request;
use EasySwoole\ORM\Exception\Exception;
use EasySwoole\RedisPool\RedisPool;
use Throwable;

class ProductService extends BaseCore
{

    use Singleton;

    /**
     * 字典数据
     * @param Request $request
     * @return Output
     * @throws Exception
     * @throws Throwable
     */
    public function getDict(Request $request) : Output
    {
        return $this->success([]);
    }

    /**
     * 创建商品
     * @param $data
     * @return Output
     * @throws DefaultException
     * @throws Exception
     * @throws Throwable
     * @throws \EasySwoole\Mysqli\Exception\Exception
     */
    public function create($data) : Output
    {
        $purchaseForm = new SubmitProductForm($data);
        $result = $purchaseForm->submit();
        return $result;
    }

    /**
     * 商品列表
     * @param Request $request
     * @return Output
     * @throws DefaultException
     * @throws Exception
     * @throws Throwable
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \EasySwoole\Redis\Exception\RedisException
     */
    public function getLists(Request $request){
        $params    = $request->getQueryParams();
        $cache     = RedisPool::defer();
        $cache_key = "productCache:lists:" . json_encode($params);
        if ($cache_data = $cache->get($cache_key)) { //缓存存在
            $data = json_decode($cache_data, true);
        } else {
            $form = new ProductListForm($params, $request);
            $data = $form->lists();
            $cache->set($cache_key, json_encode($data), BaseModel::CACHE_EXPIRE);
        }

        return $this->success($data);
    }


    /**
     * 删除记录
     * @param $selected
     * @return Output
     * @throws DefaultException
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     */
    public function deleteRecord($selected) : Output{
        is_array($selected) or $selected = [$selected];

        $result = ProductModel::deleteRecord(['id' => $selected]);
        if($result < 1){
            throw new DefaultException('操作失败');
        }

        return $this->success(['affectedRows'=>$result]);
    }
}
